package com.taobao.hsf.guide.invocationhandler;

import com.taobao.hsf.InvocationUtil;
import com.taobao.hsf.annotation.Order;
import com.taobao.hsf.invocation.Invocation;
import com.taobao.hsf.invocation.InvocationHandler;
import com.taobao.hsf.invocation.RPCResult;
import com.taobao.hsf.invocation.filter.ClientFilter;
import com.taobao.hsf.logger.LoggerInit;
import com.taobao.hsf.util.concurrent.ListenableFuture;
import com.taobao.middleware.logger.Logger;

import org.apache.commons.lang.StringUtils;

/**
 * <pre>
 *     打印客户端，拦截的具体服务
 * </pre>
 *
 * @author weipeng2k 2017年10月26日 下午15:39:01
 */
@Order(1000)
public class ClientLogInvocationTime implements ClientFilter {

    private static Logger logger = LoggerInit.LOGGER;

    private static String serviceName = System.getProperty("hsf.log.service.name");

    private static String methodName = System.getProperty("hsf.log.method.name");

    @Override
    public ListenableFuture<RPCResult> invoke(InvocationHandler nextHandler, Invocation invocation) throws Throwable {
        if (serviceName != null && StringUtils.equals(invocation.getTargetServiceUniqueName(), serviceName)) {
            if (methodName == null) {
                logger.info(
                        "ClientLogInvocationTime#invoke\n" + InvocationUtil.dumpInvocation(invocation, false, true));
            } else if (StringUtils.equals(invocation.getMethodName(), methodName)) {
                logger.info(
                        "ClientLogInvocationTime#invoke\n" + InvocationUtil.dumpInvocation(invocation, false, true));
            }
        }

        return nextHandler.invoke(invocation);
    }

    @Override
    public void onResponse(Invocation invocation, RPCResult rpcResult) {
        if (serviceName != null && StringUtils.equals(invocation.getTargetServiceUniqueName(), serviceName)) {
            StringBuilder sb = new StringBuilder();
            sb.append("ClientLogInvocationTime#onResponse\n").append(
                    InvocationUtil.dumpInvocation(invocation, false, true));
            sb.append("\n response : \n");
            sb.append("IS_ERROR:" + rpcResult.isError()).append("\n");
            sb.append("IS_TIMEOUT:" + rpcResult.isTimeout()).append("\n");
            if (rpcResult.isError()) {
                sb.append("ERROR_MESSAGE:" + rpcResult.getErrorMsg()).append("\n");
            } else {
                sb.append("RESPONSE:" + rpcResult.getAppResponse()).append("\n");
            }
            logger.info(sb.toString());
        }
    }
}
